﻿Option Explicit On
Option Strict On

Imports Microsoft.TeamFoundation.Server
Imports Microsoft.TeamFoundation.Client
Imports Microsoft.TeamFoundation.Framework.Client
Imports Microsoft.TeamFoundation.VersionControl.Client


Public Class Server
   Private myConfigurationServer As TfsConfigurationServer = Nothing


   Public Sub New(tfsServerUri As String)
      Me.New(New Uri(tfsServerUri))
   End Sub

   Public Sub New(tfsServerUri As Uri)
      myConfigurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsServerUri)
   End Sub

   Public ReadOnly Property Uri As Uri
      Get
         Return myConfigurationServer.Uri
      End Get
   End Property

   Public Function GetCollectionNames() As String()
      Dim collections As New List(Of String)

      Try
         Dim tpcService As ITeamProjectCollectionService = myConfigurationServer.GetService(Of ITeamProjectCollectionService)()

         For Each tpc As TeamProjectCollection In tpcService.GetCollections()
            collections.Add(tpc.Name)
         Next

      Catch ex As Exception
      End Try

      Return collections.ToArray
   End Function

   Public Function GetProcessTemplateNames(collectionName As String) As String()
      Dim templates As New List(Of String)

      Try
         Dim tfsCollection As TfsTeamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(New Uri(myConfigurationServer.Uri.AbsoluteUri & "/" & collectionName))
         Dim processTemplates As IProcessTemplates = CType(tfsCollection.GetService(GetType(IProcessTemplates)), IProcessTemplates)

         For Each header As TemplateHeader In processTemplates.TemplateHeaders
            templates.Add(header.Name)
         Next

      Catch ex As Exception
      End Try

      Return templates.ToArray
   End Function

   Public Function GetTeamProjectNames(collectionName As String) As String()
      Dim projects As New List(Of String)

      Try
         Dim tfsCollection As TfsTeamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(New Uri(myConfigurationServer.Uri.AbsoluteUri & "/" & collectionName))
         Dim vcAPI As VersionControlServer = CType(tfsCollection.GetService(GetType(VersionControlServer)), VersionControlServer)

         Dim tps() As TeamProject = vcAPI.GetAllTeamProjects(True)
         For Each tp As TeamProject In tps
            projects.Add(tp.Name)
         Next

      Catch ex As Exception
      End Try

      Return projects.ToArray
   End Function
End Class
